home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / pcl / src-16f.lha / code / numbers.lisp < prev    next >
Encoding:
Text File  |  1992-05-30  |  36.7 KB  |  1,227 lines

  1. ;;; -*- Mode: Lisp; Package: KERNEL; Log: code.log -*-
  2. ;;;
  3. ;;; **********************************************************************
  4. ;;; This code was written as part of the CMU Common Lisp project at
  5. ;;; Carnegie Mellon University, and has been placed in the public domain.
  6. ;;; If you want to use this code or any part of CMU Common Lisp, please contact
  7. ;;; Scott Fahlman or slisp-group@cs.cmu.edu.
  8. ;;;
  9. (ext:file-comment
  10.   "$Header: numbers.lisp,v 1.20 92/02/07 11:33:23 ram Exp $")
  11. ;;;
  12. ;;; **********************************************************************
  13. ;;;
  14. ;;; $Header: numbers.lisp,v 1.20 92/02/07 11:33:23 ram Exp $
  15. ;;;
  16. ;;; This file contains the definitions of most number functions.
  17. ;;;
  18. ;;; Author: Rob MacLachlan
  19. ;;; 
  20. ;;; Much code in this file was derived from code written by William Lott, Dave
  21. ;;; Mcdonald, Jim Large, Scott Fahlman, etc.
  22. ;;;
  23. (in-package "LISP")
  24.  
  25. (export '(zerop plusp minusp oddp evenp = /= < > <= >= max min + - * / 1+ 1- 
  26.       conjugate abs phase signum float floor ceiling truncate cis round mod
  27.           rem ffloor fceiling fround ftruncate complex realpart imagpart
  28.       logior logxor logand logeqv lognand lognor logandc1 logandc2 logorc1
  29.       logorc2 boole boole-clr boole-set boole-1 boole-2 boole-c1 boole-c2
  30.       boole-and boole-ior boole-xor boole-eqv boole-nand boole-nor
  31.       boole-andc1 boole-andc2 boole-orc1 boole-orc2 lognot logtest
  32.       logbitp ash integer-length byte byte-size byte-position
  33.       ldb ldb-test mask-field dpb deposit-field
  34.       upgraded-complex-part-type)) 
  35.  
  36. (in-package "KERNEL")
  37.  
  38.  
  39. ;;;; Number dispatch macro:
  40.  
  41. (eval-when (compile load eval)
  42.  
  43. ;;; PARSE-NUMBER-DISPATCH  --  Internal
  44. ;;;
  45. ;;;    Grovel an individual case to NUMBER-DISPATCH, augmenting Result with the
  46. ;;; type dispatches and bodies.  Result is a tree built of alists representing
  47. ;;; the dispatching off each arg (in order).  The leaf is the body to be
  48. ;;; executed in that case.
  49. ;;;
  50. (defun parse-number-dispatch (vars result types var-types body)
  51.   (cond ((null vars)
  52.      (unless (null types) (error "More types than vars."))
  53.      (when (cdr result)
  54.        (error "Duplicate case: ~S." body))
  55.      (setf (cdr result)
  56.            (sublis var-types body :test #'equal)))
  57.     ((null types)
  58.      (error "More vars than types."))
  59.     (t
  60.      (flet ((frob (var type)
  61.           (parse-number-dispatch
  62.            (rest vars)
  63.            (or (assoc type (cdr result) :test #'equal)
  64.                (car (setf (cdr result)
  65.                   (acons type nil (cdr result)))))
  66.            (rest types)
  67.            (acons `(dispatch-type ,var) type var-types)
  68.            body)))
  69.        (let ((type (first types))
  70.          (var (first vars)))
  71.          (if (and (consp type) (eq (first type) 'foreach))
  72.          (dolist (type (rest type))
  73.            (frob var type))
  74.          (frob var type)))))))
  75.  
  76.  
  77. ;;; Our guess for the preferred order to do type tests in (cheaper and/or more
  78. ;;; probable first.)
  79. ;;;
  80. (defconstant type-test-ordering
  81.   '(fixnum single-float double-float integer bignum complex ratio))
  82.  
  83. ;;; Type-Test-Order  --  Internal
  84. ;;;
  85. ;;;    Return true if Type1 should be tested before Type2.
  86. ;;;
  87. (defun type-test-order (type1 type2)
  88.   (let ((o1 (position type1 type-test-ordering))
  89.     (o2 (position type2 type-test-ordering)))
  90.     (cond ((not o1) nil)
  91.       ((not o2) t)
  92.       (t
  93.        (< o1 o2)))))
  94.  
  95.  
  96. ;;; GENERATE-NUMBER-DISPATCH  --  Internal
  97. ;;;
  98. ;;;    Return an ETYPECASE form that does the type dispatch, ordering the cases
  99. ;;; for efficiency.
  100. ;;;
  101. (defun generate-number-dispatch (vars error-tags cases)
  102.   (if vars
  103.       (let ((var (first vars))
  104.         (cases (sort cases #'type-test-order :key #'car)))
  105.     `((typecase ,var
  106.         ,@(mapcar #'(lambda (case)
  107.               `(,(first case)
  108.                 ,@(generate-number-dispatch (rest vars)
  109.                             (rest error-tags)
  110.                             (cdr case))))
  111.               cases)
  112.         (t (go ,(first error-tags))))))
  113.       cases))
  114.  
  115. ); Eval-When (Compile Load Eval)
  116.  
  117.  
  118. ;;; NUMBER-DISPATCH  --  Interface
  119. ;;;
  120. (defmacro number-dispatch (var-specs &body cases)
  121.   "NUMBER-DISPATCH ({(Var Type)}*) {((Type*) Form*) | (Symbol Arg*)}*
  122.   A vaguely case-like macro that does number cross-product dispatches.  The
  123.   Vars are the variables we are dispatching off of.  The Type paired with each
  124.   Var is used in the error message when no case matches.  Each case specifies a
  125.   Type for each var, and is executed when that signature holds.  A type may be
  126.   a list (FOREACH Each-Type*), causing that case to be repeatedly instantiated
  127.   for every Each-Type.  In the body of each case, any list of the form
  128.   (DISPATCH-TYPE Var-Name) is substituted with the type of that var in that
  129.   instance of the case.
  130.  
  131.   As an alternate to a case spec, there may be a form whose CAR is a symbol.
  132.   In this case, we apply the CAR of the form to the CDR and treat the result of
  133.   the call as a list of cases.  This process is not applied recursively."
  134.   (let ((res (list nil))
  135.     (vars (mapcar #'car var-specs))
  136.     (block (gensym)))
  137.     (dolist (case cases)
  138.       (if (symbolp (first case))
  139.       (let ((cases (apply (symbol-function (first case)) (rest case))))
  140.         (dolist (case cases)
  141.           (parse-number-dispatch vars res (first case) nil (rest case))))
  142.       (parse-number-dispatch vars res (first case) nil (rest case))))
  143.  
  144.     (collect ((errors)
  145.           (error-tags))
  146.       (dolist (spec var-specs)
  147.     (let ((var (first spec))
  148.           (type (second spec))
  149.           (tag (gensym)))
  150.       (error-tags tag)
  151.       (errors tag)
  152.       (errors `(return-from
  153.             ,block
  154.             (error 'simple-type-error :datum ,var
  155.                :expected-type ',type
  156.                :format-string
  157.                "Argument ~A is not a ~S: ~S."
  158.                :format-arguments
  159.                (list ',var ',type ,var))))))
  160.       
  161.       `(block ,block
  162.      (tagbody
  163.        (return-from ,block
  164.             ,@(generate-number-dispatch vars (error-tags)
  165.                             (cdr res)))
  166.        ,@(errors))))))
  167.  
  168.  
  169. ;;;; Binary operation dispatching utilities:
  170.  
  171. (eval-when (compile eval)
  172.  
  173. ;;; FLOAT-CONTAGION  --  Internal
  174. ;;;
  175. ;;;    Return NUMBER-DISPATCH forms for rational X float.
  176. ;;;
  177. (defun float-contagion (op x y &optional (rat-types '(fixnum bignum ratio)))
  178.   `(((single-float single-float) (,op ,x ,y))
  179.     (((foreach ,@rat-types) (foreach single-float double-float))
  180.      (,op (coerce ,x '(dispatch-type ,y)) ,y))
  181.     (((foreach single-float double-float) (foreach ,@rat-types))
  182.      (,op ,x (coerce ,y '(dispatch-type ,x))))
  183.     (((foreach single-float double-float) double-float)
  184.      (,op (coerce ,x 'double-float) ,y))
  185.     ((double-float single-float)
  186.      (,op ,x (coerce ,y 'double-float)))))
  187.  
  188.  
  189. ;;; BIGNUM-CROSS-FIXNUM  --  Internal
  190. ;;;
  191. ;;;    Return NUMBER-DISPATCH forms for bignum X fixnum.
  192. ;;;
  193. (defun bignum-cross-fixnum (fix-op big-op)
  194.   `(((fixnum fixnum) (,fix-op x y))
  195.     ((fixnum bignum)
  196.      (,big-op (make-small-bignum x) y))
  197.     ((bignum fixnum)
  198.      (,big-op x (make-small-bignum y)))
  199.     ((bignum bignum)
  200.      (,big-op x y))))
  201.  
  202. ); Eval-When (Compile Eval)
  203.  
  204.  
  205. ;;;; Canonicalization utilities:
  206.  
  207. ;;; CANONICAL-COMPLEX  --  Internal
  208. ;;;
  209. ;;;    If imagpart is 0, return realpart, otherwise make a complex.  This is
  210. ;;; used when we know that realpart and imagpart are the same type, but
  211. ;;; rational canonicalization might still need to be done.
  212. ;;;
  213. (proclaim '(inline canonical-complex))
  214. (defun canonical-complex (realpart imagpart)
  215.   (if (eql imagpart 0)
  216.       realpart
  217.       (%make-complex realpart imagpart)))
  218.  
  219.  
  220. ;;; BUILD-RATIO  --  Internal
  221. ;;;
  222. ;;;    Given a numerator and denominator with the GCD already divided out, make
  223. ;;; a canonical rational.  We make the denominator positive, and check whether
  224. ;;; it is 1.
  225. ;;;
  226. (proclaim '(inline build-ratio))
  227. (defun build-ratio (num den)
  228.   (multiple-value-bind (num den)
  229.                (if (minusp den)
  230.                (values (- num) (- den))
  231.                (values num den))
  232.     (if (eql den 1)
  233.     num
  234.     (%make-ratio num den))))
  235.  
  236.  
  237. ;;; MAYBE-TRUNCATE  --  Internal
  238. ;;;
  239. ;;;    Truncate X and Y, but bum the case where Y is 1.
  240. ;;;
  241. (proclaim '(inline maybe-truncate))
  242. (defun maybe-truncate (x y)
  243.   (if (eql y 1)
  244.       x
  245.       (truncate x y)))
  246.  
  247.  
  248. ;;;; Complexes:
  249.  
  250. (defun upgraded-complex-part-type (spec)
  251.   "Returns the element type of the most specialized COMPLEX number type that
  252.    can hold parts of type Spec.  This is currently always T."
  253.   (declare (ignore spec))
  254.   t)
  255.  
  256. (defun complex (realpart &optional (imagpart 0))
  257.   "Builds a complex number from the specified components."
  258.   (number-dispatch ((realpart real) (imagpart real))
  259.     ((rational rational)
  260.      (canonical-complex realpart imagpart))
  261.     (float-contagion %make-complex realpart imagpart (rational))))
  262.  
  263. (defun realpart (number)
  264.   "Extracts the real part of a number."
  265.   (realpart number))
  266.  
  267. (defun imagpart (number)
  268.   "Extracts the imaginary part of a number."
  269.   (imagpart number))
  270.  
  271. (defun conjugate (number)
  272.   "Returns the complex conjugate of NUMBER.  For non-complex numbers, this is
  273.   an identity."
  274.   (if (complexp number)
  275.       (complex (realpart number) (- (imagpart number)))
  276.       number))
  277.  
  278. (defun signum (number)
  279.   "If NUMBER is zero, return NUMBER, else return (/ NUMBER (ABS NUMBER))."
  280.   (if (zerop number)
  281.       number
  282.       (if (rationalp number)
  283.       (if (plusp number) 1 -1)
  284.       (/ number (abs number)))))
  285.  
  286.  
  287. ;;;; Ratios.
  288.  
  289. (defun numerator (number)
  290.   "Return the numerator of NUMBER, which must be rational."
  291.   (numerator number))
  292.  
  293. (defun denominator (number)
  294.   "Return the denominator of NUMBER, which must be rational."
  295.   (denominator number))
  296.  
  297.  
  298.  
  299. ;;;; Arithmetic Operations
  300.  
  301.  
  302. (defmacro define-arith (op init doc)
  303.   `(defun ,op (&rest args)
  304.      ,doc
  305.      (if (null args) ,init
  306.      (do ((args (cdr args) (cdr args))
  307.           (res (car args) (,op res (car args))))
  308.          ((null args) res)))))
  309.  
  310. (define-arith + 0
  311.   "Returns the sum of its arguments.  With no args, returns 0.")
  312. (define-arith * 1
  313.   "Returns the product of its arguments.  With no args, returns 1.")
  314.  
  315. (defun - (number &rest more-numbers)
  316.   "Subtracts the second and all subsequent arguments from the first.
  317.   With one arg, negates it."
  318.   (if more-numbers
  319.       (do ((nlist more-numbers (cdr nlist))
  320.        (result number))
  321.       ((atom nlist) result)
  322.          (declare (list nlist))
  323.      (setq result (- result (car nlist))))
  324.       (- number)))
  325.  
  326. (defun / (number &rest more-numbers)
  327.   "Divides the first arg by each of the following arguments, in turn.
  328.   With one arg, returns reciprocal."
  329.   (if more-numbers
  330.       (do ((nlist more-numbers (cdr nlist))
  331.        (result number))
  332.       ((atom nlist) result)
  333.          (declare (list nlist))
  334.      (setq result (/ result (car nlist))))
  335.       (/ number)))
  336.  
  337. (defun 1+ (number)
  338.   "Returns NUMBER + 1."
  339.   (1+ number))
  340.  
  341. (defun 1- (number)
  342.   "Returns NUMBER - 1."
  343.   (1- number))
  344.  
  345.  
  346. (eval-when (compile)
  347.  
  348. (defmacro two-arg-+/- (name op big-op)
  349.   `(defun ,name (x y)
  350.      (number-dispatch ((x number) (y number))
  351.        (bignum-cross-fixnum ,op ,big-op)
  352.        (float-contagion ,op x y)
  353.        
  354.        ((complex complex)
  355.     (canonical-complex (,op (realpart x) (realpart y))
  356.                (,op (imagpart x) (imagpart y))))
  357.        (((foreach bignum fixnum ratio single-float double-float) complex)
  358.     (complex (,op x (realpart y)) (imagpart y)))
  359.        ((complex (or rational float))
  360.     (complex (,op (realpart x) y) (imagpart x)))
  361.        
  362.        (((foreach fixnum bignum) ratio)
  363.     (let* ((dy (denominator y))
  364.            (n (,op (* x dy) (numerator y))))
  365.       (%make-ratio n dy)))
  366.        ((ratio integer)
  367.     (let* ((dx (denominator x))
  368.            (n (,op (numerator x) (* y dx))))
  369.       (%make-ratio n dx)))
  370.        ((ratio ratio)
  371.     (let* ((nx (numerator x))
  372.            (dx (denominator x))
  373.            (ny (numerator y))
  374.            (dy (denominator y))
  375.            (g1 (gcd dx dy)))
  376.       (if (eql g1 1)
  377.           (%make-ratio (,op (* nx dy) (* dx ny)) (* dx dy))
  378.           (let* ((t1 (,op (* nx (truncate dy g1)) (* (truncate dx g1) ny)))
  379.              (g2 (gcd t1 g1))
  380.              (t2 (truncate dx g1)))
  381.         (cond ((eql t1 0) 0)
  382.               ((eql g2 1)
  383.                (%make-ratio t1 (* t2 dy)))
  384.               (T (let* ((nn (truncate t1 g2))
  385.                 (t3 (truncate dy g2))
  386.                 (nd (if (eql t2 1) t3 (* t2 t3))))
  387.                (if (eql nd 1) nn (%make-ratio nn nd))))))))))))
  388.   
  389. ); Eval-When (Compile)
  390.  
  391.  
  392. (two-arg-+/- two-arg-+ + add-bignums)
  393. (two-arg-+/- two-arg-- - subtract-bignum)
  394.  
  395.  
  396.  
  397. (defun two-arg-* (x y)
  398.   (flet ((integer*ratio (x y)
  399.        (if (eql x 0) 0
  400.            (let* ((ny (numerator y))
  401.               (dy (denominator y))
  402.               (gcd (gcd x dy)))
  403.          (if (eql gcd 1)
  404.              (%make-ratio (* x ny) dy)
  405.              (let ((nn (* (truncate x gcd) ny))
  406.                (nd (truncate dy gcd)))
  407.                (if (eql nd 1)
  408.                nn
  409.                (%make-ratio nn nd)))))))
  410.      (complex*real (x y)
  411.        (canonical-complex (* (realpart x) y) (* (imagpart x) y))))
  412.     (number-dispatch ((x number) (y number))
  413.       (float-contagion * x y)
  414.  
  415.       ((fixnum fixnum) (multiply-fixnums x y))
  416.       ((bignum fixnum) (multiply-bignum-and-fixnum x y))
  417.       ((fixnum bignum) (multiply-bignum-and-fixnum y x))
  418.       ((bignum bignum) (multiply-bignums x y))
  419.       
  420.       ((complex complex)
  421.        (let* ((rx (realpart x))
  422.           (ix (imagpart x))
  423.           (ry (realpart y))
  424.           (iy (imagpart y)))
  425.      (canonical-complex (- (* rx ry) (* ix iy)) (+ (* rx iy) (* ix ry)))))
  426.       (((foreach bignum fixnum ratio single-float double-float) complex)
  427.        (complex*real y x))
  428.       ((complex (or rational float))
  429.        (complex*real x y))
  430.       
  431.       (((foreach bignum fixnum) ratio) (integer*ratio x y))
  432.       ((ratio integer) (integer*ratio y x))
  433.       ((ratio ratio)
  434.        (let* ((nx (numerator x))
  435.           (dx (denominator x))
  436.           (ny (numerator y))
  437.           (dy (denominator y))
  438.           (g1 (gcd nx dy))
  439.           (g2 (gcd dx ny)))
  440.      (build-ratio (* (maybe-truncate nx g1)
  441.              (maybe-truncate ny g2))
  442.               (* (maybe-truncate dx g2)
  443.              (maybe-truncate dy g1))))))))
  444.  
  445.  
  446.  
  447. ;;; INTEGER-/-INTEGER  --  Internal
  448. ;;;
  449. ;;;    Divide two integers, producing a canonical rational.  If a fixnum, we
  450. ;;; see if they divide evenly before trying the GCD.  In the bignum case, we
  451. ;;; don't bother, since bignum division is expensive, and the test is not very
  452. ;;; likely to suceed.
  453. ;;;
  454. (defun integer-/-integer (x y)
  455.   (if (and (typep x 'fixnum) (typep y 'fixnum))
  456.       (multiple-value-bind
  457.       (quo rem)
  458.       (truncate x y)
  459.     (if (zerop rem)
  460.         quo
  461.         (let ((gcd (gcd x y)))
  462.           (declare (fixnum gcd))
  463.           (if (eql gcd 1)
  464.           (build-ratio x y)
  465.           (build-ratio (truncate x gcd) (truncate y gcd))))))
  466.       (let ((gcd (gcd x y)))
  467.     (if (eql gcd 1)
  468.         (build-ratio x y)
  469.         (build-ratio (truncate x gcd) (truncate y gcd))))))
  470.  
  471.  
  472. (defun two-arg-/ (x y)
  473.   (number-dispatch ((x number) (y number))
  474.     (float-contagion / x y (ratio integer))
  475.      
  476.     ((complex complex)
  477.      (let* ((rx (realpart x))
  478.         (ix (imagpart x))
  479.         (ry (realpart y))
  480.         (iy (imagpart y))
  481.         (dn (+ (* ry ry) (* iy iy))))
  482.        (canonical-complex (/ (+ (* rx ry) (* ix iy)) dn)
  483.               (/ (- (* ix ry) (* rx iy)) dn))))
  484.     (((foreach integer ratio single-float double-float) complex)
  485.      (let* ((ry (realpart y))
  486.         (iy (imagpart y))
  487.         (dn (+ (* ry ry) (* iy iy))))
  488.        (canonical-complex (/ (* x ry) dn)
  489.               (/ (- (* x iy)) dn))))
  490.     ((complex (or rational float))
  491.      (canonical-complex (/ (realpart x) y)
  492.             (/ (imagpart x) y)))
  493.     
  494.     ((ratio ratio)
  495.      (let* ((nx (numerator x))
  496.         (dx (denominator x))
  497.         (ny (numerator y))
  498.         (dy (denominator y))
  499.         (g1 (gcd nx ny))
  500.         (g2 (gcd dx dy)))
  501.        (build-ratio (* (maybe-truncate nx g1) (maybe-truncate dy g2))
  502.             (* (maybe-truncate dx g2) (maybe-truncate ny g1)))))
  503.     
  504.     ((integer integer)
  505.      (integer-/-integer x y))
  506.     
  507.     ((integer ratio)
  508.      (if (zerop x)
  509.      0
  510.      (let* ((ny (numerator y))
  511.         (dy (denominator y))
  512.         (gcd (gcd x ny)))
  513.        (build-ratio (* (maybe-truncate x gcd) dy)
  514.             (maybe-truncate ny gcd)))))
  515.     
  516.     ((ratio integer)
  517.      (let* ((nx (numerator x))
  518.         (gcd (gcd nx y)))
  519.        (build-ratio (maybe-truncate nx gcd)
  520.             (* (maybe-truncate y gcd) (denominator x)))))))
  521.  
  522.  
  523. (defun %negate (n)
  524.   (number-dispatch ((n number))
  525.     (((foreach fixnum single-float double-float))
  526.      (%negate n))
  527.     ((bignum)
  528.      (negate-bignum n))
  529.     ((ratio)
  530.      (%make-ratio (- (numerator n)) (denominator n)))
  531.     ((complex)
  532.      (%make-complex (- (realpart n)) (- (imagpart n))))))
  533.  
  534.  
  535. ;;;; Truncate & friends.
  536.  
  537. (defun truncate (number &optional (divisor 1))
  538.   "Returns number (or number/divisor) as an integer, rounded toward 0.
  539.   The second returned value is the remainder."
  540.   (macrolet ((truncate-float (rtype)
  541.            `(let* ((float-div (coerce divisor ',rtype))
  542.                (res (%unary-truncate (/ number float-div))))
  543.           (values res
  544.               (- number
  545.                  (* (coerce res ',rtype) float-div))))))
  546.     (number-dispatch ((number real) (divisor real))
  547.       ((fixnum fixnum) (truncate number divisor))
  548.       (((foreach fixnum bignum) ratio)
  549.        (truncate (* number (denominator divisor))
  550.          (numerator divisor)))
  551.       ((fixnum bignum)
  552.        (values 0 number))
  553.       ((ratio (or float rational))
  554.        (let ((q (truncate (numerator number)
  555.               (* (denominator number) divisor))))
  556.      (values q (- number (* q divisor)))))
  557.       ((bignum fixnum)
  558.        (bignum-truncate number (make-small-bignum divisor)))
  559.       ((bignum bignum)
  560.        (bignum-truncate number divisor))
  561.       
  562.       (((foreach single-float double-float) (or rational single-float))
  563.        (if (eql divisor 1)
  564.        (let ((res (%unary-truncate number)))
  565.          (values res (- number (coerce res '(dispatch-type number)))))
  566.        (truncate-float (dispatch-type number))))
  567.       ((double-float (or single-float double-float))
  568.        (truncate-float double-float))
  569.       ((single-float double-float)
  570.        (truncate-float double-float))
  571.       (((foreach fixnum bignum ratio) (foreach single-float double-float))
  572.        (truncate-float (dispatch-type divisor))))))
  573.  
  574.  
  575. ;;; Declare these guys inline to let them get optimized a little.  Round and
  576. ;;; Fround are not declared inline since they seem too obscure and too
  577. ;;; big to inline-expand by default.  Also, this gives the compiler a chance to
  578. ;;; pick off the unary float case.  Simlarly, ceiling and floor are only
  579. ;;; maybe-inline for now, so that the power-of-2 ceiling and floor transforms
  580. ;;; get a chance.
  581. ;;;
  582. (declaim (inline rem mod fceiling ffloor ftruncate))
  583. (declaim (maybe-inline ceiling floor))
  584.  
  585. ;;; If the numbers do not divide exactly and the result of (/ number divisor)
  586. ;;; would be negative then decrement the quotient and augment the remainder by
  587. ;;; the divisor.
  588. ;;;
  589. (defun floor (number &optional (divisor 1))
  590.   "Returns the greatest integer not greater than number, or number/divisor.
  591.   The second returned value is (mod number divisor)."
  592.   (multiple-value-bind (tru rem) (truncate number divisor)
  593.     (if (and (not (zerop rem))
  594.          (if (minusp divisor)
  595.          (plusp number)
  596.          (minusp number)))
  597.     (values (1- tru) (+ rem divisor))
  598.     (values tru rem))))
  599.  
  600.  
  601. ;;; If the numbers do not divide exactly and the result of (/ number divisor)
  602. ;;; would be positive then increment the quotient and decrement the remainder by
  603. ;;; the divisor.
  604. ;;;
  605. (defun ceiling (number &optional (divisor 1))
  606.   "Returns the smallest integer not less than number, or number/divisor.
  607.   The second returned value is the remainder."
  608.   (multiple-value-bind (tru rem) (truncate number divisor)
  609.     (if (and (not (zerop rem))
  610.          (if (minusp divisor)
  611.          (minusp number)
  612.          (plusp number)))
  613.     (values (+ tru 1) (- rem divisor))
  614.     (values tru rem))))
  615.  
  616.  
  617. (defun round (number &optional (divisor 1))
  618.   "Rounds number (or number/divisor) to nearest integer.
  619.   The second returned value is the remainder."
  620.   (if (eql divisor 1)
  621.       (round number)
  622.       (multiple-value-bind (tru rem) (truncate number divisor)
  623.     (let ((thresh (/ (abs divisor) 2)))
  624.       (cond ((or (> rem thresh)
  625.              (and (= rem thresh) (oddp tru)))
  626.          (if (minusp divisor)
  627.              (values (- tru 1) (+ rem divisor))
  628.              (values (+ tru 1) (- rem divisor))))
  629.         ((let ((-thresh (- thresh)))
  630.            (or (< rem -thresh)
  631.                (and (= rem -thresh) (oddp tru))))
  632.          (if (minusp divisor)
  633.              (values (+ tru 1) (- rem divisor))
  634.              (values (- tru 1) (+ rem divisor))))
  635.         (t (values tru rem)))))))
  636.  
  637.  
  638. (defun rem (number divisor)
  639.   "Returns second result of TRUNCATE."
  640.   (multiple-value-bind (tru rem) (truncate number divisor)
  641.     (declare (ignore tru))
  642.     rem))
  643.  
  644. (defun mod (number divisor)
  645.   "Returns second result of FLOOR."
  646.   (let ((rem (rem number divisor)))
  647.     (if (and (not (zerop rem))
  648.          (if (minusp divisor)
  649.          (plusp number)
  650.          (minusp number)))
  651.     (+ rem divisor)
  652.     rem)))
  653.  
  654.  
  655. (macrolet ((frob (name op doc)
  656.          `(defun ,name (number &optional (divisor 1))
  657.         ,doc
  658.         (multiple-value-bind (res rem) (,op number divisor)
  659.           (values (float res (if (floatp rem) rem 1.0)) rem)))))
  660.   (frob ffloor floor
  661.     "Same as FLOOR, but returns first value as a float.")
  662.   (frob fceiling ceiling
  663.     "Same as CEILING, but returns first value as a float." )
  664.   (frob ftruncate truncate
  665.     "Same as TRUNCATE, but returns first value as a float.")
  666.   (frob fround round
  667.     "Same as ROUND, but returns first value as a float."))
  668.  
  669.  
  670. ;;;; Comparisons:
  671.  
  672. (defun = (number &rest more-numbers)
  673.   "Returns T if all of its arguments are numerically equal, NIL otherwise."
  674.   (do ((nlist more-numbers (cdr nlist)))
  675.       ((atom nlist) T)
  676.      (declare (list nlist))
  677.      (if (not (= (car nlist) number)) (return nil))))
  678.  
  679. (defun /= (number &rest more-numbers)
  680.   "Returns T if no two of its arguments are numerically equal, NIL otherwise."
  681.   (do* ((head number (car nlist))
  682.     (nlist more-numbers (cdr nlist)))
  683.        ((atom nlist) t)
  684.      (declare (list nlist))
  685.      (unless (do* ((nl nlist (cdr nl)))
  686.           ((atom nl) T)
  687.            (declare (list nl))
  688.            (if (= head (car nl)) (return nil)))
  689.        (return nil))))
  690.  
  691. (defun < (number &rest more-numbers)
  692.   "Returns T if its arguments are in strictly increasing order, NIL otherwise."
  693.   (do* ((n number (car nlist))
  694.     (nlist more-numbers (cdr nlist)))
  695.        ((atom nlist) t)
  696.      (declare (list nlist))
  697.      (if (not (< n (car nlist))) (return nil))))
  698.  
  699. (defun > (number &rest more-numbers)
  700.   "Returns T if its arguments are in strictly decreasing order, NIL otherwise."
  701.   (do* ((n number (car nlist))
  702.     (nlist more-numbers (cdr nlist)))
  703.        ((atom nlist) t)
  704.      (declare (list nlist))
  705.      (if (not (> n (car nlist))) (return nil))))
  706.  
  707. (defun <= (number &rest more-numbers)
  708.   "Returns T if arguments are in strictly non-decreasing order, NIL otherwise."
  709.   (do* ((n number (car nlist))
  710.     (nlist more-numbers (cdr nlist)))
  711.        ((atom nlist) t)
  712.      (declare (list nlist))
  713.      (if (not (<= n (car nlist))) (return nil))))
  714.  
  715. (defun >= (number &rest more-numbers)
  716.   "Returns T if arguments are in strictly non-increasing order, NIL otherwise."
  717.   (do* ((n number (car nlist))
  718.     (nlist more-numbers (cdr nlist)))
  719.        ((atom nlist) t)
  720.      (declare (list nlist))
  721.      (if (not (>= n (car nlist))) (return nil))))
  722.  
  723. (defun max (number &rest more-numbers)
  724.   "Returns the greatest of its arguments."
  725.   (do ((nlist more-numbers (cdr nlist))
  726.        (result number))
  727.       ((null nlist) (return result))
  728.      (declare (list nlist))
  729.      (if (> (car nlist) result) (setq result (car nlist)))))
  730.  
  731. (defun min (number &rest more-numbers)
  732.   "Returns the least of its arguments."
  733.   (do ((nlist more-numbers (cdr nlist))
  734.        (result number))
  735.       ((null nlist) (return result))
  736.      (declare (list nlist))
  737.      (if (< (car nlist) result) (setq result (car nlist)))))
  738.  
  739. (eval-when (compile eval)
  740.  
  741. (defun basic-compare (op)
  742.   `(((fixnum fixnum) (,op x y))
  743.  
  744.     ((single-float single-float) (,op x y))
  745.     (((foreach single-float double-float) double-float)
  746.      (,op (coerce x 'double-float) y))
  747.     ((double-float single-float)
  748.      (,op x (coerce y 'double-float)))
  749.     (((foreach single-float double-float) rational)
  750.      (if (eql y 0)
  751.      (,op x (coerce 0 '(dispatch-type x)))
  752.      (,op (rational x) y)))
  753.     (((foreach bignum fixnum ratio) float)
  754.      (,op x (rational y)))))
  755.  
  756.  
  757. (defmacro two-arg-</> (name op ratio-arg1 ratio-arg2 &rest cases)
  758.   `(defun ,name (x y)
  759.      (number-dispatch ((x real) (y real))
  760.        (basic-compare ,op)
  761.  
  762.        (((foreach fixnum bignum) ratio)
  763.     (,op x (,ratio-arg2 (numerator y) (denominator y))))
  764.        ((ratio integer)
  765.     (,op (,ratio-arg1 (numerator x) (denominator x)) y))
  766.        ((ratio ratio)
  767.     (,op (* (numerator (truly-the ratio x))
  768.         (denominator (truly-the ratio y)))
  769.          (* (numerator (truly-the ratio y))
  770.         (denominator (truly-the ratio x)))))
  771.        ,@cases)))
  772.  
  773. ); Eval-When (Compile Eval)
  774.  
  775. (two-arg-</> two-arg-< < floor ceiling
  776.          ((fixnum bignum)
  777.           (bignum-plus-p y))
  778.          ((bignum fixnum)
  779.           (not (bignum-plus-p x)))
  780.          ((bignum bignum)
  781.           (minusp (bignum-compare x y))))
  782.  
  783. (two-arg-</> two-arg-> > ceiling floor
  784.          ((fixnum bignum)
  785.           (not (bignum-plus-p y)))
  786.          ((bignum fixnum)
  787.           (bignum-plus-p x))
  788.          ((bignum bignum)
  789.           (plusp (bignum-compare x y))))
  790.  
  791.  
  792. (defun two-arg-= (x y)
  793.   (number-dispatch ((x number) (y number))
  794.     (basic-compare eql)
  795.  
  796.     ((fixnum (or bignum ratio)) nil)
  797.  
  798.     ((bignum (or fixnum ratio)) nil)
  799.     ((bignum bignum)
  800.      (zerop (bignum-compare x y)))
  801.  
  802.     ((ratio integer) nil)
  803.     ((ratio ratio)
  804.      (and (eql (numerator x) (numerator y))
  805.       (eql (denominator x) (denominator y))))
  806.  
  807.     ((complex complex)
  808.      (and (= (realpart x) (realpart y))
  809.       (= (imagpart x) (imagpart y))))
  810.     (((foreach fixnum bignum ratio single-float double-float) complex)
  811.      (and (= x (realpart y))
  812.       (zerop (imagpart y))))
  813.     ((complex (or float rational))
  814.      (and (= (realpart x) y)
  815.       (zerop (imagpart x))))))
  816.  
  817.  
  818. ;;; EQL -- Public
  819. ;;;
  820. (defun eql (obj1 obj2)
  821.   "Return T if OBJ1 and OBJ2 represent the same object, otherwise NIL."
  822.   (or (eq obj1 obj2)
  823.       (if (or (typep obj2 'fixnum)
  824.           (not (typep obj2 'number)))
  825.       nil
  826.       (macrolet ((foo (&rest stuff)
  827.                `(typecase obj2
  828.               ,@(mapcar #'(lambda (foo)
  829.                     (let ((type (car foo))
  830.                           (fn (cadr foo)))
  831.                       `(,type
  832.                         (and (typep obj1 ',type)
  833.                          (,fn obj1 obj2)))))
  834.                     stuff))))
  835.         (foo
  836.           (single-float eql)
  837.           (double-float eql)
  838.           (bignum
  839.            (lambda (x y)
  840.          (zerop (bignum-compare x y))))
  841.           (ratio
  842.            (lambda (x y)
  843.          (and (eql (numerator x) (numerator y))
  844.               (eql (denominator x) (denominator y)))))
  845.           (complex
  846.            (lambda (x y)
  847.          (and (eql (realpart x) (realpart y))
  848.               (eql (imagpart x) (imagpart y))))))))))
  849.  
  850.  
  851. ;;;; Logicals:
  852.  
  853. (defun logior (&rest integers)
  854.   "Returns the bit-wise or of its arguments.  Args must be integers."
  855.   (declare (list integers))
  856.   (if integers
  857.       (do ((result (pop integers) (logior result (pop integers))))
  858.       ((null integers) result))
  859.       0))
  860.  
  861. (defun logxor (&rest integers)
  862.   "Returns the bit-wise exclusive or of its arguments.  Args must be integers."
  863.   (declare (list integers))
  864.   (if integers
  865.       (do ((result (pop integers) (logxor result (pop integers))))
  866.       ((null integers) result))
  867.       0))
  868.  
  869. (defun logand (&rest integers)
  870.   "Returns the bit-wise and of its arguments.  Args must be integers."
  871.   (declare (list integers))
  872.   (if integers
  873.       (do ((result (pop integers) (logand result (pop integers))))
  874.       ((null integers) result))
  875.       -1))
  876.  
  877. (defun logeqv (&rest integers)
  878.   "Returns the bit-wise equivalence of its arguments.  Args must be integers."
  879.   (declare (list integers))
  880.   (if integers
  881.       (do ((result (pop integers) (logeqv result (pop integers))))
  882.       ((null integers) result))
  883.       -1))
  884.  
  885. (defun lognand (integer1 integer2)
  886.   "Returns the complement of the logical AND of integer1 and integer2."
  887.   (lognand integer1 integer2))
  888.  
  889. (defun lognor (integer1 integer2)
  890.   "Returns the complement of the logical OR of integer1 and integer2."
  891.   (lognor integer1 integer2))
  892.  
  893. (defun logandc1 (integer1 integer2)
  894.   "Returns the logical AND of (LOGNOT integer1) and integer2."
  895.   (logandc1 integer1 integer2))
  896.  
  897. (defun logandc2 (integer1 integer2)
  898.   "Returns the logical AND of integer1 and (LOGNOT integer2)."
  899.   (logandc2 integer1 integer2))
  900.  
  901. (defun logorc1 (integer1 integer2)
  902.   "Returns the logical OR of (LOGNOT integer1) and integer2."
  903.   (logorc1 integer1 integer2))
  904.  
  905. (defun logorc2 (integer1 integer2)
  906.   "Returns the logical OR of integer1 and (LOGNOT integer2)."
  907.   (logorc2 integer1 integer2))
  908.  
  909. (defun lognot (number)
  910.   "Returns the bit-wise logical not of integer."
  911.   (etypecase number
  912.     (fixnum (lognot (truly-the fixnum number)))
  913.     (bignum (bignum-logical-not number))))
  914.  
  915.  
  916. (macrolet ((frob (name op big-op)
  917.          `(defun ,name (x y)
  918.            (number-dispatch ((x integer) (y integer))
  919.          (bignum-cross-fixnum ,op ,big-op)))))
  920.   (frob two-arg-and logand bignum-logical-and)
  921.   (frob two-arg-ior logior bignum-logical-ior)
  922.   (frob two-arg-xor logxor bignum-logical-xor))
  923.  
  924.  
  925. (defun logcount (integer)
  926.   "Count the number of 1 bits if INTEGER is positive, and the number of 0 bits
  927.   if INTEGER is negative."
  928.   (etypecase integer
  929.     (fixnum
  930.      (logcount (truly-the (integer 0 #.(max most-positive-fixnum
  931.                         (lognot most-negative-fixnum)))
  932.               (if (minusp (truly-the fixnum integer))
  933.                   (lognot (truly-the fixnum integer))
  934.                   integer))))
  935.     (bignum
  936.      (bignum-logcount integer))))
  937.  
  938. (defun logtest (integer1 integer2)
  939.   "Predicate which returns T if logand of integer1 and integer2 is not zero."
  940.   (logtest integer1 integer2))
  941.  
  942. (defun logbitp (index integer)
  943.   "Predicate returns T if bit index of integer is a 1."
  944.   (logbitp index integer))
  945.  
  946. (defun ash (integer count)
  947.   "Shifts integer left by count places preserving sign.  - count shifts right."
  948.   (declare (integer integer count))
  949.   (etypecase integer
  950.     (fixnum
  951.      (cond ((zerop integer)
  952.         0)
  953.        ((fixnump count)
  954.         (let ((length (integer-length (truly-the fixnum integer)))
  955.           (count (truly-the fixnum count)))
  956.           (declare (fixnum length count))
  957.           (cond ((and (plusp count)
  958.               (> (+ length count)
  959.                  (integer-length most-positive-fixnum)))
  960.              (bignum-ashift-left (make-small-bignum integer) count))
  961.             (t
  962.              (truly-the fixnum
  963.                 (ash (truly-the fixnum integer) count))))))
  964.        ((minusp count)
  965.         (if (minusp integer) -1 0))
  966.        (t
  967.         (bignum-ashift-left (make-small-bignum integer) count))))
  968.     (bignum
  969.      (if (plusp count)
  970.      (bignum-ashift-left integer count)
  971.      (bignum-ashift-right integer (- count))))))
  972.  
  973. (defun integer-length (integer)
  974.   "Returns the number of significant bits in the absolute value of integer."
  975.   (etypecase integer
  976.     (fixnum
  977.      (integer-length (truly-the fixnum integer)))
  978.     (bignum
  979.      (bignum-integer-length integer))))
  980.  
  981.  
  982. ;;;; Byte operations:
  983.  
  984. (defun byte (size position)
  985.   "Returns a byte specifier which may be used by other byte functions."
  986.   (byte size position))
  987.  
  988. (defun byte-size (bytespec)
  989.   "Returns the size part of the byte specifier bytespec."
  990.   (byte-size bytespec))
  991.  
  992. (defun byte-position (bytespec)
  993.   "Returns the position part of the byte specifier bytespec."
  994.   (byte-position bytespec))
  995.  
  996. (defun ldb (bytespec integer)
  997.   "Extract the specified byte from integer, and right justify result."
  998.   (ldb bytespec integer))
  999.  
  1000. (defun ldb-test (bytespec integer)
  1001.   "Returns T if any of the specified bits in integer are 1's."
  1002.   (ldb-test bytespec integer))
  1003.  
  1004. (defun mask-field (bytespec integer)
  1005.   "Extract the specified byte from integer,  but do not right justify result."
  1006.   (mask-field bytespec integer))
  1007.  
  1008. (defun dpb (newbyte bytespec integer)
  1009.   "Returns new integer with newbyte in specified position, newbyte is right justified."
  1010.   (dpb newbyte bytespec integer))
  1011.  
  1012. (defun deposit-field (newbyte bytespec integer)
  1013.   "Returns new integer with newbyte in specified position, newbyte is not right justified."
  1014.   (deposit-field newbyte bytespec integer))
  1015.  
  1016.  
  1017. (defun %ldb (size posn integer)
  1018.   (logand (ash integer (- posn))
  1019.       (1- (ash 1 size))))
  1020.  
  1021. (defun %mask-field (size posn integer)
  1022.   (logand integer (ash (1- (ash 1 size)) posn)))
  1023.  
  1024. (defun %dpb (newbyte size posn integer)
  1025.   (let ((mask (1- (ash 1 size))))
  1026.     (logior (logand integer (lognot (ash mask posn)))
  1027.         (ash (logand newbyte mask) posn))))
  1028.  
  1029. (defun %deposit-field (newbyte size posn integer)
  1030.   (let ((mask (ash (ldb (byte size 0) -1) posn)))
  1031.     (logior (logand newbyte mask)
  1032.         (logand integer (lognot mask)))))
  1033.  
  1034.  
  1035. ;;;; Boole:
  1036.  
  1037. ;;; The boole function dispaches to any logic operation depending on
  1038. ;;;     the value of a variable.  Presently, legal selector values are [0..15].
  1039. ;;;     boole is open coded for calls with a constant selector. or with calls
  1040. ;;;     using any of the constants declared below.
  1041.  
  1042. (defconstant boole-clr 0
  1043.   "Boole function op, makes BOOLE return 0.")
  1044.  
  1045. (defconstant boole-set 1
  1046.   "Boole function op, makes BOOLE return -1.")
  1047.  
  1048. (defconstant boole-1   2
  1049.   "Boole function op, makes BOOLE return integer1.")
  1050.  
  1051. (defconstant boole-2   3
  1052.   "Boole function op, makes BOOLE return integer2.")
  1053.  
  1054. (defconstant boole-c1  4
  1055.   "Boole function op, makes BOOLE return complement of integer1.")
  1056.  
  1057. (defconstant boole-c2  5
  1058.   "Boole function op, makes BOOLE return complement of integer2.")
  1059.  
  1060. (defconstant boole-and 6
  1061.   "Boole function op, makes BOOLE return logand of integer1 and integer2.")
  1062.  
  1063. (defconstant boole-ior 7
  1064.   "Boole function op, makes BOOLE return logior of integer1 and integer2.")
  1065.  
  1066. (defconstant boole-xor 8
  1067.   "Boole function op, makes BOOLE return logxor of integer1 and integer2.")
  1068.  
  1069. (defconstant boole-eqv 9
  1070.   "Boole function op, makes BOOLE return logeqv of integer1 and integer2.")
  1071.  
  1072. (defconstant boole-nand  10
  1073.   "Boole function op, makes BOOLE return log nand of integer1 and integer2.")
  1074.  
  1075. (defconstant boole-nor   11
  1076.   "Boole function op, makes BOOLE return lognor of integer1 and integer2.")
  1077.  
  1078. (defconstant boole-andc1 12
  1079.   "Boole function op, makes BOOLE return logandc1 of integer1 and integer2.")
  1080.  
  1081. (defconstant boole-andc2 13
  1082.   "Boole function op, makes BOOLE return logandc2 of integer1 and integer2.")
  1083.  
  1084. (defconstant boole-orc1  14
  1085.   "Boole function op, makes BOOLE return logorc1 of integer1 and integer2.")
  1086.  
  1087. (defconstant boole-orc2  15
  1088.   "Boole function op, makes BOOLE return logorc2 of integer1 and integer2.")
  1089.  
  1090.  
  1091. (defun boole (op integer1 integer2)
  1092.   "Bit-wise boolean function on two integers.  Function chosen by OP:
  1093.     0    BOOLE-CLR
  1094.     1    BOOLE-SET
  1095.     2    BOOLE-1
  1096.       3    BOOLE-2
  1097.     4    BOOLE-C1
  1098.     5    BOOLE-C2
  1099.     6    BOOLE-AND
  1100.     7    BOOLE-IOR
  1101.      8    BOOLE-XOR
  1102.     9    BOOLE-EQV
  1103.     10    BOOLE-NAND
  1104.     11    BOOLE-NOR
  1105.     12    BOOLE-ANDC1
  1106.     13    BOOLE-ANDC2
  1107.     14    BOOLE-ORC1
  1108.     15    BOOLE-ORC2"
  1109.   (case op
  1110.     (0 (boole 0 integer1 integer2))
  1111.     (1 (boole 1 integer1 integer2))
  1112.     (2 (boole 2 integer1 integer2))
  1113.     (3 (boole 3 integer1 integer2))
  1114.     (4 (boole 4 integer1 integer2))
  1115.     (5 (boole 5 integer1 integer2))
  1116.     (6 (boole 6 integer1 integer2))
  1117.     (7 (boole 7 integer1 integer2))
  1118.     (8 (boole 8 integer1 integer2))
  1119.     (9 (boole 9 integer1 integer2))
  1120.     (10 (boole 10 integer1 integer2))
  1121.     (11 (boole 11 integer1 integer2))
  1122.     (12 (boole 12 integer1 integer2))
  1123.     (13 (boole 13 integer1 integer2))
  1124.     (14 (boole 14 integer1 integer2))
  1125.     (15 (boole 15 integer1 integer2))
  1126.     (t (error "~S is not of type (mod 16)." op))))
  1127.  
  1128.  
  1129. ;;;; GCD, LCM:
  1130.  
  1131. (defun gcd (&rest numbers)
  1132.   "Returns the greatest common divisor of the arguments, which must be
  1133.   integers.  Gcd with no arguments is defined to be 0."
  1134.   (cond ((null numbers) 0)
  1135.     ((null (cdr numbers)) (abs (the integer (car numbers))))
  1136.     (t
  1137.      (do ((gcd (the integer (car numbers))
  1138.            (gcd gcd (the integer (car rest))))
  1139.           (rest (cdr numbers) (cdr rest)))
  1140.          ((null rest) gcd)
  1141.        (declare (integer gcd)
  1142.             (list rest))))))
  1143.  
  1144. (defun lcm (&rest numbers)
  1145.   "Returns the least common multiple of one or more integers.  LCM of no
  1146.   arguments is defined to be 1."
  1147.   (cond ((null numbers) 1)
  1148.     ((null (cdr numbers)) (abs (the integer (car numbers))))
  1149.     (t
  1150.      (do ((lcm (the integer (car numbers))
  1151.            (lcm lcm (the integer (car rest))))
  1152.           (rest (cdr numbers) (cdr rest)))
  1153.          ((null rest) lcm)
  1154.        (declare (integer lcm) (list rest))))))
  1155.  
  1156.  
  1157. (defun two-arg-lcm (n m)
  1158.   (declare (integer n m))
  1159.   (* (truncate (max n m) (gcd n m)) (min n m)))
  1160.  
  1161.  
  1162. ;;; TWO-ARG-GCD  --  Internal
  1163. ;;;
  1164. ;;;    Do the GCD of two integer arguments.  With fixnum arguments, we use the
  1165. ;;; binary GCD algorithm from Knuth's seminumerical algorithms (slightly
  1166. ;;; structurified), otherwise we call BIGNUM-GCD.  We pick off the special case
  1167. ;;; of 0 before the dispatch so that the bignum code doesn't have to worry
  1168. ;;; about "small bignum" zeros.
  1169. ;;;
  1170. (defun two-arg-gcd (u v)
  1171.   (cond ((eql u 0) v)
  1172.     ((eql v 0) u)
  1173.     (t
  1174.      (number-dispatch ((u integer) (v integer))
  1175.        ((fixnum fixnum)
  1176.         (do ((k 0 (1+ k))
  1177.          (u (abs u) (ash u -1))
  1178.          (v (abs v) (ash v -1)))
  1179.         ((oddp (logior u v))
  1180.          (do ((temp (if (oddp u) (- v) (ash u -1))
  1181.                 (ash temp -1)))
  1182.              (nil)
  1183.            (declare (fixnum temp))
  1184.            (when (oddp temp)
  1185.              (if (plusp temp)
  1186.              (setq u temp)
  1187.              (setq v (- temp)))
  1188.              (setq temp (- u v))
  1189.              (when (zerop temp)
  1190.                (return (the fixnum (ash u k)))))))
  1191.           (declare (fixnum k u v))))
  1192.        ((bignum bignum)
  1193.         (bignum-gcd u v))
  1194.        ((bignum fixnum)
  1195.         (bignum-gcd u (make-small-bignum v)))
  1196.        ((fixnum bignum)
  1197.         (bignum-gcd (make-small-bignum u) v))))))
  1198.  
  1199.  
  1200. ;;; Primep  --  Public
  1201. ;;;
  1202. (defun primep (x)
  1203.   "Returns T iff X is a positive prime integer."
  1204.   (declare (integer x))
  1205.   (if (<= x 5)
  1206.       (and (>= x 2) (/= x 4))
  1207.       (and (not (evenp x))
  1208.        (not (zerop (rem x 3)))
  1209.        (do ((q 6)
  1210.         (r 1)
  1211.         (inc 2 (logxor inc 6)) ;; 2,4,2,4...
  1212.         (d 5 (+ d inc)))
  1213.            ((or (= r 0) (> d q)) (/= r 0))
  1214.          (declare (fixnum inc))
  1215.          (multiple-value-setq (q r) (truncate x d))))))
  1216.  
  1217.  
  1218. ;;;; Random number predicates:
  1219.  
  1220. (macrolet ((frob (name doc)
  1221.          `(defun ,name (number) ,doc (,name number))))
  1222.   (frob zerop "Returns T if number = 0, NIL otherwise.")
  1223.   (frob plusp "Returns T if number > 0, NIL otherwise.")
  1224.   (frob minusp "Returns T if number < 0, NIL otherwise.")
  1225.   (frob oddp "Returns T if number is odd, NIL otherwise.")
  1226.   (frob evenp "Returns T if number is even, NIL otherwise."))
  1227.